package fractal.model;

/** Class generate pixel array */
public class MandelbrotThread extends Thread {

	private ColorPalette palette;
	private int array[];
	private int width;
	private int height;
	private int rep;
	private boolean flag;
	private double x1;
	private double x2;
	private double y1;
	private double y2;

	/** constructor arguments: size of array */
	public MandelbrotThread(ColorPalette palette, int width, int height) {
		this.palette = palette;
		this.width = width;
		this.height = height;
		this.array = new int[width * height];
		this.flag = false;
	}

	/** method set dimensions of array */
	public void setSeting(double x1, double x2, double y1, double y2, int rep) {
		this.x1 = x1;
		this.x2 = x2;
		this.y1 = y1;
		this.y2 = y2;
		this.rep = rep;
	}

	@Override
	public void run() {
		double dx = (x2 - x1) / width;
		double dy = (y2 - y1) / height;
		double y = y1;
		int l = 0;
		int c = 0;

		for (int i = 0; i < height; i++) {
			double x = x1;
			for (int j = 0; j < width; j++) {
				c = (int) (MandelbrotFractal.value(x, y, rep) * 255.0);
				this.array[l++] = palette.getColorNr(c);
				x += dx;
			}
			y += dy;
		}
		this.flag = true;
	}

	public int[] getArray() {
		try {
			while (this.flag == false) {
				Thread.sleep(10);
			}
		} catch (Exception ex) {
			System.err.println("Thread error!\n" + ex.toString());
		}
		return this.array;
	}
}
